import React, { useState, useEffect } from 'react';
import styles from './index.module.less';
import { Card, List, InputItem } from 'antd-mobile-v2';
import Button from '@/components/button-card';
import { createForm } from '@/components/rc-form';
import { Login, GetValidCode } from '@/services/index';
import { SetToken } from '@/utils/session';
import { store } from '@/redux';


const LoginPage: React.FC<any> = (props) => {
  const { getFieldProps } = props.form;
  const [loading, setLoading] = useState(false);

  const handleLogin = (): void => {
    if (loading) {
      return;
    }
    props.form.validateFields(async (error: any, value: any) => {
      if (error) {
        return;
      }
      setLoading(true);
      const data = value;
      try {
        const res = await Login(data);
        if (res.data) {
          SetToken(res.data);
          store.dispatch({ type: 'common/clearAllCommonSaga' }); // 重置redux common的数据
          props.history.replace('/home');
        }
      } finally {
        setLoading(false);
      }
    });
  };

  const [codeImg, setCodeImg] = useState('');
  const [prevAccount, setPrevAccount] = useState('');

  // 获取图片验证码
  const getValidCode = () => {
    // rules里的{validator: ()=> {}}校验函数会劫持表单组件的操作
    const account = props.form.getFieldValue('mobile');
    const mPattern = /^1[3-9]\d{9}$/;
    if (!mPattern.test(account)) {
      return;
    }
    GetValidCode().then((res) => {
      const codeImg = 'data:image/jpeg;base64,' + res.data;
      setCodeImg(codeImg);
    });
  };

  const onAccountBlur = (curAccount: string) => {
    if (curAccount && curAccount !== prevAccount) {
      getValidCode();
      setPrevAccount(curAccount);
    }
  };

  return (
    <div className={styles['wrap']}>
      <Card className={styles['main']}>
        <Card.Body>
          <List renderHeader={<div style={{ fontSize: '16px', color: '#222222', fontWeight: 'bold' }}>登录模板应用平台</div>}>
            <InputItem
              {...getFieldProps('mobile', {
                rules: [{ required: true }]
              })}
              clear
              placeholder="请输入账号"
              onBlur={(e) => onAccountBlur(e)}
            >账号
            </InputItem>
            <InputItem
              {...getFieldProps('password', {
                rules: [{ required: true }]
              })}
              clear
              type="password"
              placeholder="请输入密码"
            >密码
            </InputItem>
            {
              codeImg &&
              <InputItem
                {...getFieldProps('imageCode', {
                  rules: [{ required: true }]
                })}
                clear
                placeholder="请输入验证码"
                maxLength="4"
                className="code-input-item"
              >验证码
                <div className={styles['code-img-box']}>
                  <img className={styles['code-img']} alt="" src={codeImg} onClick={getValidCode} />
                </div>
              </InputItem>
            }
          </List>
        </Card.Body>
        <Card.Footer
          content={
            <div className={styles['button-wrap']}>
              <Button btntype="ensure" loading={loading} onClick={handleLogin}>登录</Button>
            </div>
          }
        />
      </Card>
    </div>
  );
};

export default createForm()(LoginPage);